import logging
from typing import Optional

from fastapi import APIRouter, Query, Path

from app.controllers.origin.menu import menu_controller
from app.schemas.origin.menus import *
from app.utils.request import RequestHandler


logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/list", summary="获取菜单列表")
async def get_menus(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
):
    async def get_menu_with_children(menu_id: int):
        menu = await menu_controller.model.get(id=menu_id)
        menu_dict = await menu.to_dict()
        child_menus = await menu_controller.model.filter(parent_id=menu_id).order_by("order")
        menu_dict["children"] = [await get_menu_with_children(child.id) for child in child_menus]
        return menu_dict

    parent_menus = await menu_controller.model.filter(parent_id=0).order_by("order")
    res_menu = [await get_menu_with_children(menu.id) for menu in parent_menus]
    return RequestHandler.success_paginated(data=res_menu, total=len(res_menu), page=page, page_size=page_size)


@router.get("/{menu_id}", summary="获取菜单详情")
async def get_menu(
    menu_id: int = Path(..., description="菜单ID"),
):
    result = await menu_controller.get(id=menu_id)
    return RequestHandler.success(data=result)


@router.post("/create", summary="创建菜单")
async def create_menu(
    menu_in: MenuCreate,
):
    await menu_controller.create(obj_in=menu_in)
    return RequestHandler.success(message="创建成功")


@router.put("/{menu_id}", summary="更新菜单")
async def update_menu(
    menu_id: int = Path(..., description="菜单ID"),
    menu_in: MenuUpdate = None,
):
    if menu_in:
        menu_in.id = menu_id
    await menu_controller.update(id=menu_id, obj_in=menu_in)
    return RequestHandler.success(message="更新成功")


@router.delete("/{menu_id}", summary="删除菜单")
async def delete_menu(
    menu_id: int = Path(..., description="菜单ID"),
):
    child_menu_count = await menu_controller.model.filter(parent_id=menu_id).count()
    if child_menu_count > 0:
        return RequestHandler.error(message="无法删除有子菜单的菜单")
    await menu_controller.remove(id=menu_id)
    return RequestHandler.success(message="删除成功")
